import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { BackendService } from "../backend.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private router: Router,private backend: BackendService) { }

  error: string;
  form: FormGroup = new FormGroup({
    username: new FormControl(''),
    password: new FormControl(''),
  });
  ngOnInit(): void {
  }
  submit() {
    if (this.form.valid) {
      let loginform = this.form.value;
      console.log(loginform);
      if (loginform.username.trim().length == 0) {
        console.log(loginform, loginform.username.length)
        return;
      }
      this.error = "";
      this.backend.login(loginform).subscribe(result => {
        if (result.ok) {
          this.backend.username = loginform.username;
          this.router.navigate(["home"]);
        } else {
          if(result.message){//通过互联网登录验证，会返回message
            this.error = result.message;
          }else{
            this.error = "密码错误！请输入正确的密码";
          }          
        }
      });

    }
  }
}
